package com.ycd.Util;


import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.*;
import java.util.*;

/*
 * jdbc工具类
 * @Data 2022-3-10
 * */
public class jdbcUtil {

    private static DataSource dataSource;
    private static Properties properties;

    /*
     * 设置驱动执行一次
     * */
    static {
        properties=new Properties();
        try {
            properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
            dataSource=DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * 获取连接方法
     * @ return  数据库连接
     * */
    public static Connection getCon() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    /*
     * 释放资源
     * */
    public static void closeAll(Connection conn, Statement stmt, ResultSet rs) {

        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static List<Map<String,String>> query(String sql, Object obj[]){

        //List是用来存储所有查询到的数据
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        ResultSet rs = null;
        Connection conn=null;
        PreparedStatement ps=null;
        try {
            conn=getCon(); //每次查询的时候调用一次获取连接的方法,因为我们连接每次操作完毕都关闭了

            //4、获取处理对象 Statement或 PrepareStatement

            ps = conn.prepareStatement(sql);
//			通过ps对象设置参数值
            //数组里面有几个参数,我就设置几次
            for(int i = 0;i < obj.length;i++){
                //parameterIndex 参数下标   值
                ps.setObject(i+1, obj[i]);
            }

            //5.执行并处理结果集
            rs = ps.executeQuery();

            ResultSetMetaData rsmd = rs.getMetaData(); //获取结果集表结构
            while(rs.next()){
                Map<String,String> map = new HashMap<String,String>();
                //把查询的每条记录数据都放在map里面
                //有多少列,那么就往map里面put()几次
                for(int j = 1;j <= rsmd.getColumnCount();j++){
                    map.put(rsmd.getColumnName(j),rs.getString(j));
                }

                list.add(map);
            }

        }  catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally { //无论是否有一次,都执行
            //6.关闭资源
            closeAll(conn,ps,rs);
        }
        return list;
    }

}
